<?php

namespace App\Jobs;
use App\Models\Order;
use App\Models\Subscribe;
use App\Services\PublishTemplateService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class OrderDeliverJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $order_id;

    /**
     * Create a new job instance.
     * PublishLotteryJob constructor.
     * @param $order_id
     */
    public function __construct($order_id)
    {
        $this->order_id = $order_id;
    }

    /**
     * Execute the job.
     * @link https://shimo.im/mindmaps/y6ydprxxxJKCggPx/
     * @return void
     */
    public function handle()
    {
        $order = Order::with('product_snapshot')->find($this->order_id);
        if (!$order)
            return;

        $subscribe = Subscribe::where('type', Subscribe::TYPE_ORDER_DELIVER)->where('user_id', $order->user_id)->withCertain('user', ['openid'])->first();
        if ($subscribe) {
            $service = new PublishTemplateService();
            $service->order_deliver($subscribe->user->openid, $order->product_snapshot->title, $order->express_title, $order->express_sn, $order->updated_at);
            $subscribe->delete();
        }
    }

}
